package com.ydy.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.ydy.domain.Brand;
import com.ydy.domain.Goods;
import com.ydy.domain.GoodsKind;
import com.ydy.service.GoodsService;

@Controller
public class GoodsController {

	@Resource
	private GoodsService goodsService;
	
	@RequestMapping("/list")
	public String list(Model model,Goods g,@RequestParam(defaultValue = "1")Integer pageNum,@RequestParam(defaultValue = "3")Integer pageSize) {
		PageInfo<Goods> info = goodsService.list(g,pageNum,pageSize);
		model.addAttribute("g", g);
		model.addAttribute("info", info);
		
		return "list";
	}
	@GetMapping("/show")
	public String show(Model model,String id) {
		Goods g = goodsService.show(id);
		model.addAttribute("g", g);
		
		return "show";
	}
	@GetMapping("/update")
	public String update(String id,Model model) {
		List<Brand> list1 = goodsService.getBrand();
		List<GoodsKind> list2 = goodsService.getGoodsKind();
		model.addAttribute("b", list1);
		model.addAttribute("gk", list2);
		Goods g = goodsService.show(id);
		model.addAttribute("g", g);
		
		return "update";
	}
	@GetMapping("/add")
	public String add(Model model) {
		//获取商品品牌和种类
		List<Brand> list1 = goodsService.getBrand();
		List<GoodsKind> list2 = goodsService.getGoodsKind();
		model.addAttribute("b", list1);
		model.addAttribute("gk", list2);
		return "add";
	}
	@PostMapping("/add")
	public String add(Goods g,@RequestParam("file")MultipartFile file) throws IllegalStateException, IOException {
		if(file != null && file.getSize()>0) {
			String path="d:pic";
			String name=UUID.randomUUID().toString()+file.getOriginalFilename();
			File file2 = new File(name);
			file.transferTo(file2);
			//g.setPic("/pic/"+name);
			}
		goodsService.add(g);
		
		return "redirect:list";
	}
	@PostMapping("/update")
	public String update(Goods g) {
		goodsService.update(g);
		return "redirect:list";
	}
	@ResponseBody
	@PostMapping("/dels")
	public boolean dels(@RequestParam("ids[]")Integer[] ids) {
		int i = goodsService.dels(ids);
		return i>0;
	}
}
